package cn.tworice.upload.web;


import cn.tworice.common.annotation.NoEncryption;
import cn.tworice.upload.constand.UploadConst;
import cn.tworice.upload.service.UploadService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * wangEditor 相关组件
 * @author 二饭[tworice@sina.cn][2022/2/12 22:12]
 */
@RestController
@RequestMapping("editor")
@Slf4j
@CrossOrigin
@Api(tags = "富文本文件上传")
public class EditorController {

    @Autowired
    private UploadService uploadService;

    @PostMapping("upload")
    @NoEncryption
    @Deprecated
    public Map<String, Object> upload(MultipartFile editorFile, String url) {
        Map<String, Object> result = new HashMap<>();
        String path="/receive/preview/"+ uploadService.uploadFile(editorFile);
        result.put("errno", 0);
        result.put("data", new String[]{url+path});
        return result;
    }

    /**
     * 配置wangEditor5的图片上传
     *
     * @param editorFile 文件
     * @param request    Request对象
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author 二饭 [2022/5/21]
     **/
    @PostMapping("editorUpload")
    @NoEncryption
    public Map<String, Object> upload5(MultipartFile editorFile, @RequestParam(defaultValue = "") String agent, HttpServletRequest request) {
        String serverName = request.getServerName();
        String scheme = request.getScheme();
        String url = scheme + "://" + serverName + ":" + request.getServerPort();

        Map<String, Object> result = new HashMap<>();
        try {
            String path = agent + UploadConst.preview + uploadService.uploadFile(editorFile);
            Map<String, String> map = new HashMap<>();
            map.put("url", url + "/" + path);
            result.put("errno", 0);
            result.put("data", map);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
        return result;
    }

}
